<template>
  <div class="followUp">
    <div class="title">
      <p></p>
      <p>随访表单</p>
      <p v-if="state.followUpObj.obj && state.followUpObj.obj.tag == 1">AI随访结果待核验</p>
      <p class="on" v-if="state.followUpObj.obj && state.followUpObj.obj.tag == 2">待人工随访</p>
    </div>
    <div class="followUpForm" v-if="state.context">
      <a-spin :spinning="state.formSpinning" tip="加载中...">
        <!-- 随访表单组件 -->
        <!-- :disabled="state.followUpObj.obj.tag == 1 ? true : false" -->
        <!-- templateName -->
        <div class="formWrap forms">
          <div class="templateName">{{ state.followUpObj.obj.templateName }}</div>
          <tform
            :formData="state.context"
            :disabled="state.followUpObj.obj.status == 0 ? false : true"
          ></tform>
        </div>
        <div class="btn" v-if="state.followUpObj.obj.status == 0 && state.followUpObj.obj.tag == 1">
          <a-button type="primary" @click="verificationPassed">核验通过</a-button>
          <a-button @click="createFollowUp">创建人工随访</a-button>
        </div>
        <div class="btn" v-if="state.followUpObj.obj.status == 0 && state.followUpObj.obj.tag == 2">
          <a-button type="primary" @click="verificationPassed">提交随访结果</a-button>
          <a-button class="fail" @click="createFollowUpTwo">随访失败</a-button>
        </div>
      </a-spin>
    </div>
    <a-empty v-else class="mt30">
      <template #description>
        <span> 暂无随访表单 </span>
      </template>
    </a-empty>
    <a-modal
      class="createForm"
      v-model:open="state.isShow"
      title="创建人工随访"
      @cancel="resetForm"
      :maskClosable="false"
    >
      <a-spin :spinning="state.followUpSpinning" tip="加载中...">
        <a-form ref="formRef" :model="formState" :rules="rules">
          <a-form-item class="date" label="选择随访时间" required name="date1">
            <a-date-picker
              v-model:value="formState.date1"
              :disabledDate="disabledDate"
              type="date"
              placeholder="请选择随访时间"
              format="YYYY-MM-DD"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="选择随访表单" name="region" class="date chooseForm">
            <a-select
              v-model:value="formState.region"
              placeholder="请选择随访表单"
              @change="selectFormFun"
              show-search
              optionFilterProp="label"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            >
              <a-select-option
                v-for="(item, index) in state.followUpObj.templateList"
                :key="index"
                :value="item.id"
                :label="item.templateName"
                >{{ item.templateName }}</a-select-option
              >
            </a-select>
            <div class="chooseCheck">
              <a-checkbox v-model:checked="state.checkedForm" @change="chooseFormFun"
                >选择原表单</a-checkbox
              >
            </div>
          </a-form-item>
          <a-form-item label="选择随访医生" name="region2" class="date chooseForm">
            <a-select
              v-model:value="formState.region2"
              placeholder="请选择随访医生"
              @change="selectDoctorFun"
              show-search
              optionFilterProp="label"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            >
              <a-select-option
                v-for="(item, index) in state.followUpObj.doctorList"
                :key="index"
                :value="item.id"
                :label="item.realName"
                >{{ item.realName }}</a-select-option
              >
            </a-select>
            <div class="chooseCheck">
              <a-checkbox v-model:checked="state.checkDoctor" @change="chooseDoctorFun"
                >选择原医生</a-checkbox
              >
            </div>
          </a-form-item>
          <div class="border"></div>
          <a-form-item class="btn">
            <a-button style="margin-right: 10px" @click="resetForm">取消</a-button>
            <a-button type="primary" @click="onSubmit">确定</a-button>
          </a-form-item>
        </a-form>
      </a-spin>
      <template v-slot:footer></template>
    </a-modal>
    <a-modal
      class="createForm"
      v-model:open="state.isShowTwo"
      title="随访失败处理"
      @cancel="resetFormTwo"
      :maskClosable="false"
    >
      <a-spin :spinning="state.followUpSpinning" tip="加载中...">
        <a-form ref="formRef" :model="formState" :rules="rules">
          <a-form-item
            class="date chooseForm failTitle"
            ref="name"
            label="随访失败原因"
            name="failReason"
          >
            <a-input v-model:value="formState.failReason" placeholder="请输入随访失败原因" />
            <div class="reasonTitle">
              <p
                @click="reasonTitleFun(item)"
                v-for="(item, index) in state.reasonList"
                :key="index"
              >
                {{ item.name }}
              </p>
            </div>
          </a-form-item>
          <div class="task">创建新的随访任务</div>
          <a-form-item class="date" label="选择随访时间" required name="date1">
            <a-date-picker
              v-model:value="formState.date1"
              type="date"
              placeholder="请选择随访时间"
              :disabledDate="disabledDate"
              format="YYYY-MM-DD"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="选择随访表单" name="region" class="date chooseForm">
            <a-select
              v-model:value="formState.region"
              placeholder="请选择随访表单"
              @change="selectFormFun"
              show-search
              optionFilterProp="label"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            >
              <a-select-option
                v-for="(item, index) in state.followUpObj.templateList"
                :key="index"
                :value="item.id"
                :label="item.templateName"
                >{{ item.templateName }}</a-select-option
              >
            </a-select>
            <div class="chooseCheck">
              <a-checkbox v-model:checked="state.checkedForm" @change="chooseFormFun"
                >选择原表单</a-checkbox
              >
            </div>
          </a-form-item>
          <a-form-item label="选择随访医生" name="region2" class="date chooseForm">
            <a-select
              v-model:value="formState.region2"
              placeholder="请选择随访医生"
              @change="selectDoctorFun"
              show-search
              optionFilterProp="label"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            >
              <a-select-option
                v-for="(item, index) in state.followUpObj.doctorList"
                :key="index"
                :value="item.id"
                :label="item.realName"
                >{{ item.realName }}</a-select-option
              >
            </a-select>
            <div class="chooseCheck">
              <a-checkbox v-model:checked="state.checkDoctor" @change="chooseDoctorFun"
                >选择原医生</a-checkbox
              >
            </div>
          </a-form-item>
          <div class="border"></div>
          <a-form-item class="btn">
            <a-button style="margin-right: 10px" @click="resetFormTwo">取消</a-button>
            <a-button type="primary" @click="onSubmitTwo">确定</a-button>
          </a-form-item>
        </a-form>
      </a-spin>
      <template v-slot:footer></template>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import { transformTime } from '@/assets/hmmJs/index.js'
import { followSave, followUpdate } from '@/api/patientManagement/index.ts'
import tform from '@/components/TForm/index.vue'
import dayjs from 'dayjs'
const route = useRoute()
const props = defineProps(['childProp'])
const state = reactive({
  // 1 AI随访结果待核验   2 待人工随访
  followUpObj: {
    obj: {
      tag: null
    },
    templateList: [],
    doctorList: [],
    context: null
  },
  context: null,
  templateId: '',
  userId: '',
  isShow: false,
  isShowTwo: false,
  checkedForm: false,
  checkDoctor: false,
  followUpSpinning: false,
  formSpinning: false,
  reasonList: [
    {
      name: '联系失败',
      id: 1
    },
    {
      name: '患者无法沟通',
      id: 2
    },
    {
      name: '患者拒绝采访',
      id: 3
    }
  ]
})
watch(
  props,
  (newValue) => {
    if (newValue.childProp && newValue.childProp.id) {
      state.followUpObj = newValue.childProp
      state.context = null
      state.templateId =
        newValue.childProp.obj && newValue.childProp.obj.templateId
          ? newValue.childProp.obj.templateId
          : ''
      state.userId =
        newValue.childProp.obj && newValue.childProp.obj.userId ? newValue.childProp.obj.userId : ''
      if (newValue.childProp.obj && newValue.childProp.obj.context) {
        state.context = JSON.parse(newValue.childProp.obj.context)
      }
    }
  },
  { immediate: true, deep: true }
)
const formRef = ref()
const formState: UnwrapRef<FormState> = reactive({
  failReason: '',
  date1: undefined,
  region: undefined,
  regionName: '',
  region2: undefined,
  region2Name: ''
})
const rules = {
  failReason: [{ required: true, message: '请输入随访失败原因', trigger: 'blur' }],
  date1: [{ required: true, message: '请选择随访时间', trigger: 'change', type: 'object' }],
  region: [{ required: true, message: '选择随访表单', trigger: 'change' }],
  region2: [{ required: true, message: '请选择随访医生', trigger: 'change' }]
}
const emit = defineEmits(['resetDetail'])
const verificationPassed = () => {
  let param = {
    id: '',
    context: '',
    status: 3,
    tag: 3
  }
  //   if (route.query.id) {
  //     param.id = route.query.id
  //   } else {
  //     param.id = state.followUpObj.id
  //   }
  param.id = state.followUpObj.id
  param.context = JSON.stringify(state.context)
  state.formSpinning = true
  followUpdate(param)
    .then((res) => {
      state.formSpinning = false
      if (state.followUpObj.obj.tag == 1) {
        message.success('核验通过')
      } else {
        message.success('提交随访结果成功')
      }
      state.context = null
      emit('resetDetail')
    })
    .catch(() => {
      state.formSpinning = false
    })
}
const reasonTitleFun = (item) => {
  formState.failReason = item.name
}
const disabledDate = (current) => {
  //   当天之前的不可选（包括当天）
  return current && current < dayjs().endOf('day')
  //   当天之前的不可选（不包括当天）
  //   return current && current < dayjs().subtract(1, 'days').endOf('day')
}

const createFollowUp = () => {
  nextTick(() => {
    formState.date1 = undefined
    formState.region = undefined
    formState.region2 = undefined
    state.checkedForm = false
    state.checkDoctor = false
    state.isShow = true
  })
}
const createFollowUpTwo = () => {
  nextTick(() => {
    formState.date1 = undefined
    formState.region = undefined
    formState.region2 = undefined
    state.checkedForm = false
    state.checkDoctor = false
    state.isShowTwo = true
  })
}

const selectFormFun = (item) => {
  formState.region = item
  for (let i = 0; i < state.followUpObj.templateList.length; i++) {
    if (item == state.followUpObj.templateList[i].id) {
      formState.regionName = state.followUpObj.templateList[i].templateName
    }
  }
  if (formState.region == state.templateId) {
    state.checkedForm = true
  } else {
    state.checkedForm = false
  }
}
const chooseFormFun = () => {
  if (state.checkedForm == true) {
    for (let i = 0; i < state.followUpObj.templateList.length; i++) {
      if (state.templateId == state.followUpObj.templateList[i].id) {
        formState.regionName = state.followUpObj.templateList[i].templateName
      }
    }
    formState.region = Number(state.templateId)
  } else {
    formState.region = undefined
  }
}
const selectDoctorFun = (item) => {
  formState.region2 = item
  if (formState.region2 == state.userId) {
    state.checkDoctor = true
  } else {
    state.checkDoctor = false
  }
}
const chooseDoctorFun = () => {
  if (state.checkDoctor == true) {
    formState.region2 = Number(state.userId)
  } else {
    formState.region2 = undefined
  }
}
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      let remindTime = transformTime(formState.date1, 4)
      let param = {
        id: state.followUpObj.obj.id,
        tag: 4,
        status: 4
      }
      state.formSpinning = true
      followUpdate(param)
        .then((res) => {
          state.formSpinning = false
          emit('resetDetail')
        })
        .catch(() => {
          state.formSpinning = false
        })
      let paramTwo = {
        patId: state.followUpObj.obj.patId,
        patName: state.followUpObj.obj.patName,
        deptCode: state.followUpObj.obj.deptCode,
        deptName: state.followUpObj.obj.deptName,
        userId: formState.region2,
        remindTime: remindTime,
        planTime: remindTime,
        followTime: remindTime,
        status: 0,
        templateId: formState.region,
        templateName: formState.regionName,
        tag: 2,
        manageType: 2,
        context: state.followUpObj.obj.context,
        isRead: false,
        diseaseGroup: state.followUpObj.obj.diseaseGroup,
        groupId: state.followUpObj.obj.groupId,
        reason: state.followUpObj.obj.reason
      }
      state.followUpSpinning = true
      followSave(paramTwo)
        .then((res) => {
          state.followUpSpinning = false
          message.success('创建成功')
          state.isShow = false
        })
        .catch(() => {
          state.followUpSpinning = false
        })
    })
    .catch((error: ValidateErrorEntity<FormState>) => {
      console.log('error', error)
    })
}
const onSubmitTwo = () => {
  formRef.value
    .validate()
    .then(() => {
      let remindTime = transformTime(formState.date1, 4)
      let param = {
        id: state.followUpObj.obj.id,
        failReason: formState.failReason,
        tag: 4,
        status: 4
      }
      state.formSpinning = true
      followUpdate(param)
        .then((res) => {
          state.formSpinning = false
          emit('resetDetail')
        })
        .catch(() => {
          state.formSpinning = false
        })
      let paramTwo = {
        patId: state.followUpObj.obj.patId,
        patName: state.followUpObj.obj.patName,
        deptCode: state.followUpObj.obj.deptCode,
        deptName: state.followUpObj.obj.deptName,
        userId: formState.region2,
        remindTime: remindTime,
        planTime: remindTime,
        followTime: remindTime,
        status: 0,
        templateId: formState.region,
        templateName: formState.regionName,
        tag: 2,
        manageType: 2,
        context: state.followUpObj.obj.context,
        isRead: false,
        diseaseGroup: state.followUpObj.obj.diseaseGroup,
        groupId: state.followUpObj.obj.groupId,
        reason: state.followUpObj.obj.reason
      }
      state.formSpinning = true
      followSave(paramTwo)
        .then((res) => {
          state.formSpinning = false
          message.success('创建成功')
          state.isShowTwo = false
        })
        .catch(() => {
          state.formSpinning = false
        })
    })
    .catch((error: ValidateErrorEntity<FormState>) => {
      console.log('error', error)
    })
}
const resetForm = () => {
  state.isShow = false
  formRef.value.resetFields()
}
const resetFormTwo = () => {
  state.isShowTwo = false
  formRef.value.resetFields()
}
</script>
<style lang="less" scoped>
.mt30 {
  margin-top: 30px;
}
.followUp {
  .title {
    p {
      font-size: 18px;
      color: #1d2129;
      font-weight: 600;
      display: inline-block;
      vertical-align: middle;
      margin: 0;
      &:nth-child(1) {
        width: 3px;
        height: 16px;
        background: #165dff;
        margin-right: 10px;
      }
      &:nth-child(3) {
        font-size: 14px;
        color: #f53f3f;
        font-weight: 700;
        margin-left: 8px;
        background: #ffece8;
        padding: 2px 8px;
      }
      &.on {
        color: #165dff;
        background: #e8f3ff;
      }
    }
  }
  .followUpForm {
    width: 800px;
    margin: 25px auto 0;
    .forms {
      border: 1px solid #e5e6eb;
      min-height: 300px;
      padding: 30px 50px;
      .templateName {
        text-align: center;
        font-size: 20px;
        color: #1d2129;
        font-weight: 700;
      }
    }
    .btn {
      margin-top: 16px;
      color: #4e5969;
      font-size: 14px;
      .ant-btn {
        &:nth-child(1) {
          border-color: #165dff;
          background: #165dff;
          margin-right: 8px;
          color: #fff;
        }
        &.fail {
          border-color: #f53f3f;
          color: #f53f3f;
        }
      }
    }
  }
}
</style>
<style>
.createForm .ant-modal-content {
  padding: 0;
}
.createForm .ant-modal-header {
  border-bottom: 1px solid #e5e6eb;
  padding: 12px 20px;
  margin-bottom: 24px;
}
.createForm .ant-modal-header .ant-modal-title {
  color: #1d2129;
}
.createForm .ant-modal-body {
  padding: 0 20px;
}
.createForm .ant-form .ant-form-item.date {
  width: 370px;
}
.createForm .ant-form .ant-form-item.date.failTitle {
  width: 100%;
}
.createForm .ant-form .ant-form-item.date.failTitle .reasonTitle p {
  display: inline-block;
  vertical-align: middle;
  font-size: 12px;
  font-weight: 700;
  color: #f53f3f;
  padding: 2px 8px;
  margin: 8px 8px 0 0;
  background: #ffece8;
  border-radius: 2px;
}
.createForm .ant-form .ant-form-item.date.failTitle .reasonTitle p:hover {
  cursor: pointer;
  opacity: 0.8;
}
.createForm .ant-form .task {
  padding: 6px 16px;
  background: #f7f8fa;
  margin-bottom: 24px;
  font-size: 14px;
  color: #1d2129;
  font-weight: 700;
}
.createForm .ant-form .ant-form-item.btn {
  padding: 16px 0;
  text-align: right;
}
.createForm .ant-form .border {
  border-bottom: 1px solid #e5e6eb;
}
.createForm .ant-form .ant-form-item.date.chooseForm {
  position: relative;
}
.createForm .ant-form-item.chooseForm .ant-col {
  display: inline-block;
  vertical-align: middle;
}
.createForm .ant-form-item.chooseForm .ant-col .chooseCheck {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: -120px;
}
.createForm .ant-col .chooseCheck .ant-checkbox-inner {
  border-radius: 50%;
}
.createForm .ant-col .chooseCheck .ant-checkbox.ant-checkbox-checked:after {
  border-radius: 50%;
  transition: all 0.01s;
}
.createForm .ant-col .chooseCheck .ant-checkbox-inner::after {
  display: none;
}
.createForm .ant-col .chooseCheck .ant-checkbox-inner::before {
  content: '';
  width: 6px;
  height: 6px;
  background: #fff;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
}
</style>
